
import ColorType from "./enum/color";

const { ccclass, property } = cc._decorator;

@ccclass
export default class BallBox extends cc.Component {

    @property([cc.SpriteFrame])
    num: cc.SpriteFrame[] = Array<cc.SpriteFrame>();

    @property([cc.SpriteFrame])
    color:cc.SpriteFrame[] = Array<cc.SpriteFrame>();

    @property(cc.Prefab)
    ball: cc.Prefab
    //@ts-ignore
    balls:[{ num: number, color: ColorType }] = [
        { num: null, color: null },
        { num: null, color: null },
        { num: null, color: null },
        { num: null, color: null },
        { num: null, color: null },
        { num: null, color: null },
    ]

    

    onLoad() {
        cc.systemEvent.on('gamestart', this.init, this)

        cc.systemEvent.on('getBall', function (balls) {
            for (let index = 0; index < balls.length; index++) {
                const element = balls[index];
                this.balls.push(element)
                this.balls.splice(0,1)
            }
            this.drawBall()
        },this)
    }


    start() {
        
    }

    // update (dt) {}

    init() {
    }
    clearAll() {
        this.node.removeAllChildren()
    }

    drawBall() {
        this.clearAll()
            for (let index = 0; index < 6; index++) {
                const element = this.balls[index];
                if (element != undefined) {
                    const ball =   this.setBallStyle(element.color,element.num)
                    this.node.addChild(ball)
                }
            }
            
    }

    setBallStyle(color:ColorType,num:number):cc.Node{
        const newBall = cc.instantiate(this.ball)
        if(color != null && num != null){
            let bg =  newBall.getChildByName('Background').getComponent(cc.Sprite)
            let ft =  newBall.getChildByName('Background').getChildByName("font") .getComponent(cc.Sprite)
            let ballbg = newBall.getComponent(cc.Button) as cc.Button
            ballbg.normalSprite = this.color[color]
            ballbg.pressedSprite = this.color[color]
            ballbg.disabledSprite = this.color[color]
            bg.spriteFrame = this.color[color]
            ft.spriteFrame = this.num[num-1]
        }else{
            // newBall.opacity = 0
        }
        return newBall
    }
}



